package com.budwk.app.sqfwV2.generator.lanhuadu.pdf;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.BasePdfParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.BaseTemplatePdfGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.SqfwPdfCreateCommonBO;
import com.budwk.app.sqfwV2.component.DayingRoadPdfComponent;
import com.budwk.app.sqfwV2.component.ProblemComponent;
import com.budwk.app.sqfwV2.dto.dto.FireSafetyOnDayingRoadPdfDTO;
import com.budwk.app.sqfwV2.enums.lanHuaDu.LanHuaDuFileServiceEnum;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 整改复查意见书，版本号1.0
 */

@Slf4j
public class lhdRecReDocGenerator extends BaseTemplatePdfGenerator{

    /**
     * 当该场所上一次巡查存在限期整改问题时，本次巡查生成该文档。
     *      1 场所面积 > 300
     *      2 上一次的数据是期限整改，本次已整改
     * @param pdfDTO
     * @return
     */
    @Override
    public boolean pdfCreateConditionCheck(SqfwPdfCreateCommonBO pdfDTO) {
        if (pdfDTO.isDownTemplate()) {
            return true;
        }
        FireSafetyOnDayingRoadPdfDTO roadPdfDTO = ProblemComponent.getSafetyPdfDTO(pdfDTO);
        // 初始数据 没有复查数据
        if (StringUtils.isEmpty(roadPdfDTO.getLastSummaryId())) {
            return false;
        }
        if(new BigDecimal(roadPdfDTO.getPlaceArea()).compareTo(new BigDecimal(300)) < 1){
            return false;
        }
        // 检查上次的数据是否存在期限整改
        SqfwFormsummaryNewService formsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
        Sqfw_formSummary_new lastData = formsummaryNewService.fetch(roadPdfDTO.getLastSummaryId());
        FireSafetyOnDayingRoadPdfDTO lastPdfDto = JSONObject.parseObject(lastData.getParamData(), FireSafetyOnDayingRoadPdfDTO.class);
        Integer isRectified = lastPdfDto.getIsRectified();
        if (isRectified == 3) {
            // 上一次的数据存在期限整改
            return true;
        }
        return false;
    }

    @Override
    public String getTemplateName() {
        return LanHuaDuFileServiceEnum.E.getFilePath();
    }


    private void bulidBase(Map<String, Object> paramMap, FireSafetyOnDayingRoadPdfDTO roadPdfDTO, SqfwPdfCreateCommonBO pdfDTO) {
        BasePdfParamDTO basePdfParam = pdfDTO.getBasePdfParamDTO();
        paramMap.put("placeName", StrUtil.formatStr(roadPdfDTO.getPlaceName()));
        paramMap.put("fillDate", DateUtil.format(basePdfParam.getFillDate(), DatePattern.CHINESE_DATE_PATTERN));

        // 安全生产行政执法人员
        BasePdfParamDTO basePdfParamDTO = pdfDTO.getBasePdfParamDTO();
        String peers = StrUtil.formatStr(basePdfParamDTO.getCreateUserName());
        if (StringUtils.isNotEmpty(roadPdfDTO.getPeers())) {
            peers = String.format("%s%s%s", StrUtil.formatStr(basePdfParamDTO.getCreateUserName()), ",", roadPdfDTO.getPeers());
        }
        paramMap.put("peers", peers);
        paramMap.put("operator", StrUtil.formatStr(roadPdfDTO.getOperator()));
        paramMap.put("mobile", StrUtil.formatStr(roadPdfDTO.getOperatorTelephone()));

        // {市}{区}{街道}
        String area = String.format("%s%s%s", StrUtil.formatZhiShu(basePdfParam.getCity()), StrUtil.formatZhiShu(basePdfParam.getDistrict()), StrUtil.formatZhiShu(basePdfParam.getCounty()));
        paramMap.put("sqj", area);
    }

    @Override
    public void customerPopularPdfParam(Map<String, Object> paramMap, SqfwPdfCreateCommonBO pdfDTO) {
        if (pdfDTO.isDownTemplate()) {  // 下载模板
            buildNullData(paramMap);
            return;
        }
        FireSafetyOnDayingRoadPdfDTO roadPdfDTO = DayingRoadPdfComponent.getFireSafetyOnDayingRoadPdfDTO(paramMap, pdfDTO);
        // 1 构建基本信息
        bulidBase(paramMap, roadPdfDTO, pdfDTO);
        // 2 构建措施
        paramMap.put("mes",buildMes(roadPdfDTO));
        // 3 隐患内容
        paramMap.put("text", buildHidderContent(roadPdfDTO));
    }

    private String buildHidderContent(FireSafetyOnDayingRoadPdfDTO roadPdfDTO) {
        // 1 获取当前的隐患措施
        List<String> curHidderStr = getHidderStr(roadPdfDTO.getExistDangerStr());
        // 未整改的隐患
        String noStr = StringUtils.EMPTY;
        if (curHidderStr.size() > 0) {
            noStr = String.format("%s%s%s%s", "\"", String.join("; ", curHidderStr), "\"", "未整改。    ");
        }
        SqfwFormsummaryNewService formsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
        Sqfw_formSummary_new lastData = formsummaryNewService.fetch(roadPdfDTO.getLastSummaryId());
        FireSafetyOnDayingRoadPdfDTO lastPdfDto = JSONObject.parseObject(lastData.getParamData(), FireSafetyOnDayingRoadPdfDTO.class);
        // 将本次的隐患内容删除得到已经整改的内容体
        // 上一次的隐患
        List<String> lastHidderStr = getHidderStr(lastPdfDto.getExistDangerStr());
        String yesStr = StringUtils.EMPTY;
        if (lastHidderStr.size() > 0) {
            // 已整改的隐患
            List<String> minus = lastHidderStr.stream().filter(item -> !curHidderStr.contains(item)).collect(Collectors.toList());
            if (minus.size() > 0) {
                yesStr = String.format("%s%s%s%s", "\"", String.join("; ", minus), "\"", "已整改。");
            }
        }
        return String.format("%s%s", noStr, yesStr);
    }


    private String buildMes(FireSafetyOnDayingRoadPdfDTO roadPdfDTO) {
        String rectifyingMeasures = roadPdfDTO.getRectifyingDangersMeasures();
        if (StringUtils.isEmpty(rectifyingMeasures)) {
            return StringUtils.EMPTY;
        }
        String str = rectifyingMeasures.replaceAll("\n", "").replaceAll("\\d+", "");
        String[] split = str.split(";");
        List<String> mesList = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            if (StringUtils.isNotEmpty(split[i])) {
                mesList.add(split[i]);
            }
        }
        return String.join(";", mesList);
    }


    private void buildNullData(Map<String, Object> paramMap) {
        paramMap.put("placeName", "");
        paramMap.put("fillDate", "");
        paramMap.put("mes", "");
        paramMap.put("text", "");
        paramMap.put("peers", "");
        paramMap.put("operator", "");
        paramMap.put("mobile", "");
        paramMap.put("sqj", "XX区XX街道");
        paramMap.put("county", "XX街道");
    }

    private List<String> getHidderStr(String text) {
        if (StringUtils.isEmpty(text)) {
            return Lists.newArrayList();
        }
        String str = text.replaceAll("\n", "").replaceAll("\\d+", "");
        String[] split = str.split(";");
        return List.of(split);
    }
}
